<template>
  <el-dialog v-model="dialogVisible" width="800px" @close="close">
    <template #default>
      <el-form :model="userForm" label-width="90px" class="user-editor-form">
        <el-form-item label="用户名" prop="username" class="inline">
          <el-input v-model="userForm.username" show-word-limit placeholder="请输入用户名" />
        </el-form-item>

        <!-- <el-form-item v-if="!userForm.id" label="密码" prop="password" class="inline">
          <el-input
            v-model="userForm.password"
            type="password"
            show-word-limit
            placeholder="请输入用户密码"
          />
        </el-form-item> -->

        <el-form-item label="真实姓名" prop="realName" class="inline">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email" class="inline">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="性别" prop="gender" class="inline">
          <el-select v-model="userForm.gender" placeholder="请选择性别">
            <el-option
              v-for="item in dicts.system_global_gender"
              :key="item.v"
              :label="item.k"
              :value="userForm.gender == item.v ? userForm.gender : item.v"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone" class="inline">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item label="启用状态" prop="enabled" class="inline">
          <el-radio-group v-model="userForm.enabled">
            <el-radio
              v-for="item in dicts.system_global_status"
              :key="item.v"
              :label="userForm.enabled == item.v ? userForm.enabled : item.v"
              :value="item.v"
            >
              {{ item.k }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="分配角色" prop="roleIds" class="inline">
          <el-tree-select
            class="treeList"
            v-model="userForm.roleIds"
            placeholder="请选择分配角色"
            :render-after-expand="false"
            :data="roleTree"
            :props="{ label: 'roleName' }"
            :auto-expand-parent="true"
            :default-expand-all="true"
            node-key="id"
            show-checkbox
            multiple
          />
        </el-form-item>
        <el-form-item
          label=""
          style="visibility: hidden"
          prop="roleIds"
          class="inline"
        ></el-form-item>
        <el-form-item label="所属组织" prop="unitId" class="inline">
          <el-tree
            ref="menuTreeRef"
            placeholder="请选择所属组织"
            :data="permission.treeList"
            :props="permission.treeProps"
            :default-expanded-keys="defaultExpand"
            :check-strictly="true"
            show-checkbox
            node-key="id"
            class="tree"
            @check="toggleTreeChecked"
          >
          </el-tree>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            type="textarea"
            placeholder="请输入备注内容"
            v-model="userForm.remark"
            :maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount, getCurrentInstance, ComponentInternalInstance } from 'vue'
import { rolePage, userAdd, userGet, userUpdate } from '@api/systemUser'
import { organizationTree } from '@api/systemUnit'
import { Organization } from '@interface/systemUnit'
import { IRole, IUser } from '@/interface/systemUser'
import { ElTree } from 'element-plus'

import { ElMessage } from 'element-plus'
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  userUpdateId: {
    type: String,
    default: ''
  }
})

const menuTreeRef = ref<InstanceType<typeof ElTree>>()
const defaultExpand = ref<number[]>([])
const dialogVisible = ref(props.dialogVisible)
const userUpdateId = ref(props.userUpdateId)
//表单数据
const userForm = reactive<Partial<IUser>>({
  username: '',
  // password: '',
  realName: '',
  email: '',
  gender: '',
  phone: '',
  enabled: '',
  unitId: '',
  roleIds: [],
  remark: ''
})

const permission = reactive({
  treeList: [] as unknown as Organization,
  treeProps: {
    label: 'name'
  }
})
const getOrganizationMenuTree = async () => {
  const Tree = await organizationTree()
  const { data } = Tree
  permission.treeList = data
}

//角色列表
const roleTree = ref<IRole[]>([])
const getRolePage = async () => {
  const res = await rolePage({
    current: 1,
    size: 999
  })
  const { records } = res.data
  roleTree.value = records
}

onBeforeMount(async () => {
  const { proxy } = getCurrentInstance() as ComponentInternalInstance
  if (proxy) {
    ;(proxy as any).getDicts(['system_global_gender', 'system_global_status'])
  }
  //编辑获取详情
  if (userUpdateId.value != '') {
    const updateData = await userGet(userUpdateId.value)
    const { roleIds, user } = updateData.data
    Object.assign(userForm, user)
    menuTreeRef.value!.setCheckedKeys([user.unitId])
    defaultExpand.value = [user.unitId]
    userForm.enabled = userForm.enabled ? '1' : '0'
    userForm.roleIds = roleIds
  }
  //所属组织
  getOrganizationMenuTree()
  //角色列表
  getRolePage()
})

const toggleTreeChecked = (data, checkObj) => {
  // 共两个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、树目前的选中状态对象
  // 树目前的选中状态对象，包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性
  if (checkObj.checkedKeys.length != 0) {
    if (checkObj.checkedKeys.length == 2) {
      // 如果选择超过一个节点，则只保留最后一个节点
      //单选实现
      menuTreeRef.value!.setCheckedKeys([data.id])
    }
  }
}

//添加
const addUser = async () => {
  const res = await userAdd(userForm)
  if (res.code != '200') {
    ElMessage({
      type: 'error',
      message: res.message
    })
    return
  } else {
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
  }
}
//修改
const updateUser = async () => {
  const res = await userUpdate(userForm)
  if (res.code != '200') {
    ElMessage({
      type: 'error',
      message: res.message
    })
    return
  } else {
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
  }
}
//关闭dialog
// eslint-disable-next-line vue/valid-define-emits
const emit = defineEmits()
const close = () => {
  emit('update:dialogVisible', false)
  emit('userChange')
}
//确认
const onSubmit = async () => {
  const unitIdInfo = menuTreeRef.value!.getCheckedKeys() as string[]
  const [unitId] = unitIdInfo
  userForm.unitId = unitId
  if (userUpdateId.value != '') {
    await updateUser()
  } else {
    await addUser()
  }
  emit('userChange')
  close()
}
</script>

<style lang="scss" scoped>
.user-editor-form {
  :deep(.inline) {
    display: inline-flex;
    vertical-align: middle;
    width: 50%;
  }

  .treeList {
    padding: 2px;
    width: 100%;
  }
}
.inline {
  display: inline-flex;
  vertical-align: middle;
  width: 50%;
}
.tree {
  // margin-top: 0.5rem;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 0.5rem;
  padding: 5px;
  flex: 1;
  height: 20vh;
  overflow: auto;
}
</style>
